<template>
    <div>
        <!-- 内容 -->
        <slot />
        <div
            ref="loadingTarget"
            class="h-6 py-4"
        >
            <!-- 加载更多 -->
            <m-svg-icon
                v-show="model"
                class="w-4 h-4 mx-auto animate-spin"
                name="infinite-load"
            ></m-svg-icon>
            <!-- 没有更多数据 -->
            <p
                v-if="isFinished"
                class="text-center text-base text-zinc-400"
            >
                已经没有更多数据了
            </p>
        </div>
    </div>
</template>

<script setup>
import { useIntersectionObserver } from '@vueuse/core'
import { ref, watch } from 'vue'

const props = defineProps({
    //数据是否全部加载完成
    isFinished: {
        type: Boolean,
        default: false
    }
})

const model = defineModel()
const emits = defineEmits(['onLoad'])
const loadingTarget = ref(null)

//记录当前是否在底部的一个变量
const targetIsIntersecting = ref(false)
useIntersectionObserver(loadingTarget, ([{ isIntersecting }]) => {
    targetIsIntersecting.value = isIntersecting
    emitLoad()
})

/**
 * 触发load事件
 */
const emitLoad = () => {
    // 当加载更多的视图可见时，处理加载更多的逻辑
    if (targetIsIntersecting.value && !model.value && !props.isFinished) {
        model.value = true
        emits('onLoad')
    }
}

// 监听loading 的变化，解决数据加载完成之后，首屏未铺满的问题
watch(model, () => {
    console.log(model.value)
    setTimeout(() => {
        emitLoad()
    }, 100)
})
</script>
<style lang="scss" scope></style>
